package com.qinglei.recoup.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.pojo.AddFloorParam;
import com.qinglei.recoup.system.pojo.FloorPageParam;
import com.qinglei.recoup.system.pojo.FloorShowVO;
import com.qinglei.recoup.system.pojo.TimePeriodParam;
import com.qinglei.recoup.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zxy
 */
@Api(tags = "层 相关控制器-张-已实现")
@RestController
@RequestMapping("/floor")
public class FloorController {

    @Autowired
    private FloorService floorService;

    @Autowired
    private BedService bedService;

    @Autowired
    private RadarBedService radarBedService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private BuildingService buildingService;

    @Autowired
    private MonitorTimeService monitorTimeService;

    @Autowired
    private SystemConfigService systemConfigService;

    @ApiOperation(value = "分页查询层")
    @GetMapping("/showPage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "buildingId", value = "楼id", paramType = "query", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页码，从1开始，默认是1", paramType = "query", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页条数，默认20", paramType = "query", dataType = "Integer")
    })
    public CommonRes<IPage<FloorShowVO>> showPageFloor(FloorPageParam floorPageParam) {
        return floorService.showPageFloor(floorPageParam);
    }

    @ApiOperation(value = "添加层")
    @PostMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "buildingId", value = "楼id", paramType = "body", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "name", value = "层名称", paramType = "body", dataType = "String", required = true)})
    public CommonRes addFloor(@RequestBody AddFloorParam addFloorParam) {
        Integer integer = floorService.getBaseMapper().selectCount(Wrappers.<Floor>lambdaQuery()
                .eq(Floor::getBuildingId,addFloorParam.getBuildingId())
                .eq(Floor::getName,addFloorParam.getName()));
        if (integer > 0){
            return CommonRes.failed("层名称重复");
        }
        Floor floor = new Floor();
        BeanUtils.copyProperties(addFloorParam,floor);
        Building building = buildingService.getBaseMapper().selectById(addFloorParam.getBuildingId());
        //离床时间阈值
        floor.setOutBedTimeout(building.getOutBedTimeout());
        floor.setOutBedTimeoutUnified(building.getOutBedTimeoutUnified());
        //监测时间
        floor.setMonitorTimeUnified(building.getMonitorTimeUnified());
        int count = floorService.getBaseMapper().insert(floor);
        List<TimePeriodParam> monitorTimeByObjIdandtype = monitorTimeService.getMonitorTimeByObjIdAndType(addFloorParam.getBuildingId(), SystemConfigService.TYPE_TAKE_EVENT_TIMEOUT);
        if (monitorTimeByObjIdandtype.size() > 0){
            for (TimePeriodParam mtq:monitorTimeByObjIdandtype) {
                MonitorTime monitorTime = new MonitorTime();
                BeanUtils.copyProperties(mtq,monitorTime);
                monitorTime.setObjId(floor.getId());
                monitorTime.setType(SystemConfigService.TYPE_OUT_BED_TIMEOUT);
                monitorTimeService.getBaseMapper().insert(monitorTime);
            }
        }else {
            List<TimePeriodParam> monitorTimeList = systemConfigService.getDefaultMonitorTime();
            for (TimePeriodParam sc : monitorTimeList) {
                MonitorTime monitorTime = new MonitorTime();
                monitorTime.setStartTime(sc.getStartTime());
                monitorTime.setEndTime(sc.getEndTime());
                monitorTime.setObjId(floor.getId());
                monitorTime.setType(SystemConfigService.TYPE_OUT_BED_TIMEOUT);
                monitorTimeService.getBaseMapper().insert(monitorTime);
            }
        }
        if (count>0){
            return CommonRes.ok();
        }
        return CommonRes.failed("新增层失败");
    }

    @ApiOperation(value = "通过层id查询层")
    @GetMapping("/{id}")
    @ApiImplicitParam(name = "id", value = "层id", paramType = "path", dataType = "Integer")
    public CommonRes<FloorShowVO> getFloorById(@PathVariable Integer id) {
        Floor floor = floorService.getBaseMapper().selectById(id);
        FloorShowVO floorShowVO = new FloorShowVO();
        BeanUtils.copyProperties(floor,floorShowVO);
        return CommonRes.ok(floorShowVO);
    }

    @ApiOperation(value = "修改层信息")
    @PutMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "层id", paramType = "body", dataType = "Integer",required = true),
            @ApiImplicitParam(name = "name", value = "层名称", paramType = "body", dataType = "String",required = true)})
    public CommonRes addRadar(@RequestBody FloorShowVO floorShowVO) {
        Floor floor1 = floorService.getBaseMapper().selectById(floorShowVO.getId());
        Integer integer = floorService.getBaseMapper().selectCount(Wrappers.<Floor>lambdaQuery()
                .eq(Floor::getName,floorShowVO.getName())
                .eq(Floor::getBuildingId,floor1.getBuildingId())
                .last("and id != "+floorShowVO.getId()));
        if (integer > 0){
            return CommonRes.failed("层名称重复");
        }
        Floor floor = new Floor();
        BeanUtils.copyProperties(floorShowVO,floor);
        int count = floorService.getBaseMapper().updateById(floor);
        if (count > 0){
            return CommonRes.ok();
        }
        return CommonRes.failed("修改层信息失败");
    }

    @ApiOperation(value = "通过层id删除层")
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    @ApiImplicitParam(name = "id", value = "层id", paramType = "path", dataType = "Integer",required = true)
    public CommonRes delFloorById(@PathVariable Integer id) {
        List<Bed> beds = bedService.getBaseMapper().selectList(Wrappers.<Bed>lambdaQuery().eq(Bed::getFloorId, id));
        for (Bed b:beds) {
            Integer bedCount = radarBedService.getBaseMapper().selectCount(Wrappers.<RadarBed>lambdaQuery().eq(RadarBed::getBedId, b.getId()));
            if (bedCount > 0) {
                return CommonRes.failed("该楼层已有床位绑定监测仪，不能删除，如果想删除，请先解绑监测仪");
            }
        }
        Floor floor = floorService.getById(id);
        if (floor == null) {
            return CommonRes.failed("该层信息不存在");
        }
        int count = floorService.getBaseMapper().deleteById(id);
        if (count > 0){
            roomService.getBaseMapper().delete(Wrappers.<Room>lambdaUpdate().eq(Room::getFloorId,id));
            int deleteCnt = bedService.getBaseMapper().delete(Wrappers.<Bed>lambdaUpdate().eq(Bed::getFloorId, id));
            buildingService.subBedCnt(floor.getBuildingId(), deleteCnt);
            return CommonRes.ok();
        }
        return CommonRes.failed("删除层信息失败");
    }


    @ApiOperation(value = "添加一个层床位数量")
    @PutMapping("/add/{id}")
    @ApiImplicitParam(name = "id", value = "楼id", paramType = "path", dataType = "Integer",required = true)
    public CommonRes addBedCnt(@PathVariable Integer id) {
        return floorService.addBedCnt(id);
    }


    @ApiOperation(value = "减少一个层床位数量")
    @PutMapping("/sub/{id}")
    @ApiImplicitParam(name = "id", value = "楼id", paramType = "path", dataType = "Integer",required = true)
    public CommonRes subBedCnt(@PathVariable Integer id) {
        return floorService.subBedCnt(id, 1);
    }

    @ApiOperation(value = "通过楼id查层")
    @GetMapping("/getFloor/{buildingId}")
    @ApiImplicitParam(name = "id", value = "楼id", paramType = "path", dataType = "Integer",required = true)
    public CommonRes getFloor(@PathVariable Integer buildingId) {
        List<Floor> floors = floorService.getBaseMapper().selectList(Wrappers.<Floor>lambdaQuery().eq(Floor::getBuildingId, buildingId));
        Floor floor = new Floor();
        floor.setName("全部");
        floors.add(0,floor);
        return CommonRes.ok(floors);
    }
}
